package myJs.tools

import myJs.Implicits._
import myJs.{FileSaver, Utils}
import myJs.Utils._
import myJs.genome.Search
import myJs.myPkg._
import myJs.myPkg.jquery._
import myJs.tool.Tool
import org.scalajs.dom._
import org.scalajs.dom.ext.Ajax
import scalatags.Text.all
import scalatags.Text.all._

import scala.scalajs.js
import scala.scalajs.js.Dynamic.{global => g}
import scala.scalajs.js.annotation.{JSExport, JSExportTopLevel}
import scala.concurrent.ExecutionContext.Implicits.global

/**
 * Created by yz on 16/9/2021
 */
@JSExportTopLevel("SeqFetch")
object SeqFetch {

  val multipleId = "multiple"
  val singleId = "single"
  val formId = "form"

  def singleFormJq=$(s"#${singleId} #${formId}")

  def multipleFormJq=$(s"#${multipleId} #${formId}")

  @JSExport("init")
  def init = {
    refreshSpecies
    refreshChrTypeahead
    bootStrapValidator
    registerEvent
  }

  def refreshSpecies = {
    val speciesMap = Tool.speciesMap
    val html = speciesMap.zipWithIndex.map { case ((k,v), i) =>
      label(
        marginRight := 15,
        width := 250,
      )(input(
        `type` := "radio",
        name := "species",
        value := k,
        if (i == 0) checked else all.raw(""),
        onchange := s"Search.geneIdExampleChange(this)"
      )(v)
      )
    }.mkString
   singleFormJq.find(s"#species").empty().html(html)
   multipleFormJq.find(s"#species").empty().html(html)
  }

  def refreshChrTypeahead = {
    val formJq = singleFormJq
    val species = formJq.find(s":input[name='species']:checked").`val`().toString
    val url = g.jsRoutes.controllers.GenomeController.getAllChrs().url.toString
    Ajax.get(url = s"${url}?species=${species}", headers = Map("Content-Type" -> "application/json")).map { xhr =>
      val rs = xhr.responseText.toJArS
      formJq.findInputByName(s"chr").typeahead("destroy").
        typeahead(TypeaheadOptions.source(rs)
        )
    }
  }

  def registerEvent = {
    $(document.body).on("click", s".myMultipleSearch", "", (y: Element) => {
     multiSearch
    })
    $(document.body).on("click", s".myShowExample", "", (y: Element) => {
      showExample(y)
    })
    $(document.body).on("click", s".myDownload", "", (y: Element) => {
      download
    })
    $(document.body).on("click", s".mySingleSearch", "", (y: Element) => {
      singleSearch
    })
    $(".myMainUl a[data-toggle='tab']").on("shown.bs.tab", (y: Element, e: Event) => {
      $("#result").hide()
    })
  }

  def showExample(y: Element) = {
    val inputJq = $(y).parents(".form-group").find(":input")
    val str = $(y).text().trim
    inputJq.`val`(str)
    inputJq.parents(s"#${formId}").bv.revalidateField(inputJq)
  }

  def singleSearch = {
    val formJq = singleFormJq
    val bv = formJq.bv
    bv.validate()
    val valid = bv.isValid()
    if (valid) {
      val element = div(id := "content",
        span(id := "info", "Query...",
          span(id := "progress")), " ",
        img(src := "/assets/images/running2.gif", cls := "runningImage", width := 30, height := 20)
      ).render
      val layerOptions = LayerOptions(icon=16,shade=0.01,time=20000000)
      val index = layer.msg(element, layerOptions)
      val url = g.jsRoutes.controllers.ToolsController.seqQuery().url.toString
      Ajax.post(url = s"${url}", data = formJq.serialize(), headers = Map("Content-Type" -> "application/x-www-form-urlencoded"),
        responseType = "application/json").map { xhr =>
        layer.close(index)
        val rs = xhr.responseText.toJDJAn
        val valid = rs("valid").toB
        if (valid) {
          $("#queryText").`val`(rs.myGet("data"))
          $("#result").show()
        } else {
          g.swal("Error", rs.myGet("message"), "error")
          $("#result").hide()
        }
      }
    }
  }

  def multiSearch = {
    val formJq = multipleFormJq
    val bv = formJq.bv
    bv.validate()
    val valid = bv.isValid()
    if (valid) {
      val element = div(id := "content",
        span(id := "info", "Query...",
          span(id := "progress")), " ",
        img(src := "/assets/images/running2.gif", cls := "runningImage", width := 30, height := 20)
      ).render
      val layerOptions = LayerOptions(icon=16,shade=0.01,time=20000000)
      val index = layer.msg(element, layerOptions)
      val url = g.jsRoutes.controllers.ToolsController.seqMultipleQuery().url.toString
      Ajax.post(url = s"${url}", data = formJq.serialize(), headers = Map("Content-Type" -> "application/x-www-form-urlencoded"),
        responseType = "application/json").map { xhr =>
        layer.close(index)
        val rs = xhr.responseText.toJDJAn
        val valid = rs("valid").toB
        if (valid) {
          $("#queryText").`val`(rs.myGet("data"))
          $("#result").show()
        } else {
          g.swal("Error", rs.myGet("message"), "error")
          $("#result").hide()
        }
      }
    }
  }

  def download = {
    val fileName = "seq.fa"
    val content =  $("#queryText").myVal
    val blob = new Blob(js.Array(content),
      BlobPropertyBag(`type` = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8"))
    FileSaver.saveAs(blob, fileName)
  }

  def bootStrapValidator = {
    singleBootStrapValidator
    multipleBootStrapValidator
  }

  def singleBootStrapValidator = {
    val maxNumber = Double.MaxValue
    val dict: js.Dictionary[js.Any] = js.Dictionary(
      "feedbackIcons" -> js.Dictionary(
        "valid" -> "glyphicon glyphicon-ok",
        "invalid" -> "glyphicon glyphicon-remove",
        "validating" -> "glyphicon glyphicon-refresh",
      ),
      "fields" -> js.Dictionary(
        "chr" -> {
          val info = "Chromosome"
          js.Dictionary(
            "validators" -> js.Dictionary(
              "notEmpty" -> js.Dictionary(
                "message" -> s"${info} is required！"
              ),
            )
          )
        },
        "start" -> {
          val info = "Start"
          js.Dictionary(
            "validators" -> js.Dictionary(
              "notEmpty" -> js.Dictionary(
                "message" -> s"${info} is required！"
              ),
              "integer" -> js.Dictionary(
                "message" -> s"${info} must be integer！",
              ),
            )
          )
        },
        "end" -> {
          val info = "End"
          js.Dictionary(
            "validators" -> js.Dictionary(
              "notEmpty" -> js.Dictionary(
                "message" -> s"${info} is required！"
              ),
              "integer" -> js.Dictionary(
                "message" -> s"${info} must be integer！",
              ),
            )
          )
        },
      )
    )
   singleFormJq.bootstrapValidator(dict)
  }

  def multipleBootStrapValidator = {
    val maxNumber = Double.MaxValue
    val dict: js.Dictionary[js.Any] = js.Dictionary(
      "feedbackIcons" -> js.Dictionary(
        "valid" -> "glyphicon glyphicon-ok",
        "invalid" -> "glyphicon glyphicon-remove",
        "validating" -> "glyphicon glyphicon-refresh",
      ),
      "fields" -> js.Dictionary(
        "region" -> {
          val info = "Region"
          js.Dictionary(
            "validators" -> js.Dictionary(
              "notEmpty" -> js.Dictionary(
                "message" -> s"${info} is required！"
              ),
            )
          )
        },
      )
    )
   multipleFormJq.bootstrapValidator(dict)
  }


}
